import sys, os, random
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, 
    QGridLayout, QHBoxLayout, QVBoxLayout, QGroupBox,
    QPushButton, QLabel, QComboBox
)
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtCore import Qt

from setting import *
from styles import *
from utils import get_names_from_folder
from Ban_Widget import BanWidget
# 各资源文件夹（在 images/ 下）
survivor_avatar_names = get_names_from_folder(os.path.join("images", "survivor_avarter"), ".jpg")
hunter_avatar_names   = get_names_from_folder(os.path.join("images", "hunter_avarter"), ".jpg")

survivor_role_names   = get_names_from_folder(os.path.join("images", "survivor"), ".jpg")
hunter_role_names     = get_names_from_folder(os.path.join("images", "hunter"), ".jpg")
active_ability_names  = get_names_from_folder(os.path.join("images", "active_ability"), ".jpg")
survivor_talent_names = get_names_from_folder(os.path.join("images", "survivor_talent"), ".jpg")
hunter_talent_names   = get_names_from_folder(os.path.join("images", "hunter_talent"), ".jpg")

survivor_ban_names    = get_names_from_folder(os.path.join("images", "survivor_ban"), ".jpg")
hunter_ban_names      = get_names_from_folder(os.path.join("images", "hunter_ban"), ".jpg")

map_names             = get_names_from_folder(os.path.join("images", "map"), ".jpg")


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("第五人格娱乐赛抽奖 —— 作者：Dirgeo、JQ神仙、克兰德")
        self.resize(1300, 900)

        # 记录：上一场选手(确认后)，上一次抽取(未确认)
        self.last_match_players = set()
        self.prev_draw_survivors = set()
        self.prev_draw_hunter = None

        # 当前本场选手
        self.this_match_survivors = []
        self.this_match_hunter = None

        # 设置全局样式
        self.setStyleSheet(app_global_style)

        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout(main_widget)
        main_layout.setSpacing(10)



        # 顶部按钮区
        button_layout_top = QHBoxLayout()
        self.btn_draw_players = QPushButton("抽取选手")
        button_layout_top.addWidget(self.btn_draw_players)

        # 底部按钮区
        button_layout_bottom = QHBoxLayout()
        self.btn_survivor_role = QPushButton("抽取求生角色(4)")
        self.btn_hunter_role = QPushButton("抽取监管者角色(4)")
        self.btn_survivor_talent = QPushButton("抽取求生天赋(4)")
        self.btn_hunter_talent = QPushButton("抽取监管者天赋(1)")
        self.btn_hunter_active_skill = QPushButton("抽取监管者主动技能(1)")
        self.btn_map = QPushButton("抽取地图")
        self.btn_one_key = QPushButton("一键抽取")
        self.btn_reset = QPushButton("重置")

        button_layout_bottom.addWidget(self.btn_survivor_role)
        button_layout_bottom.addWidget(self.btn_hunter_role)
        button_layout_bottom.addWidget(self.btn_survivor_talent)
        button_layout_bottom.addWidget(self.btn_hunter_talent)
        button_layout_bottom.addWidget(self.btn_hunter_active_skill)
        button_layout_bottom.addWidget(self.btn_map)
        button_layout_bottom.addWidget(self.btn_one_key)
        button_layout_bottom.addWidget(self.btn_reset)

        main_layout.addLayout(button_layout_top)
        main_layout.addLayout(button_layout_bottom)

        # ========== 求生者(4人) ==========
        self.group_survivors = QGroupBox("求生者（4人）")
        self.group_survivors.setStyleSheet(outer_groupbox_style)
        surv_layout = QVBoxLayout(self.group_survivors)
        surv_layout.setSpacing(10)

        # 1) 选手信息(4头像+名字)
        self.survivors_info_box = QGroupBox("选手信息")
        self.survivors_info_box.setStyleSheet(inner_groupbox_style)
        info_layout = QHBoxLayout(self.survivors_info_box)
        self.survivor_avatar_labels = []
        self.survivor_name_labels = []
        for _ in range(4):
            v = QVBoxLayout()
            v.setSpacing(5)
            avatar = QLabel()
            avatar.setFixedSize(AVATAR_SIZE, AVATAR_SIZE)
            avatar.setAlignment(Qt.AlignCenter)
            avatar.setStyleSheet(global_label_style)

            name_label = QLabel()
            name_label.setAlignment(Qt.AlignCenter)
            name_label.setMinimumHeight(30)

            v.addWidget(avatar, alignment=Qt.AlignCenter)
            v.addWidget(name_label, alignment=Qt.AlignCenter)
            info_layout.addLayout(v)
            self.survivor_avatar_labels.append(avatar)
            self.survivor_name_labels.append(name_label)

        # 2) 天赋
        self.survivors_talent_box = QGroupBox("天赋")
        self.survivors_talent_box.setStyleSheet(inner_groupbox_style)
        talent_layout = QHBoxLayout(self.survivors_talent_box)
        self.survivor_talent_images = []
        self.survivor_talent_names = []
        for _ in range(4):
            v = QVBoxLayout()
            v.setSpacing(5)
            t_img = QLabel()
            t_img.setFixedSize(TALENT_IMG_SIZE, TALENT_IMG_SIZE)
            t_img.setAlignment(Qt.AlignCenter)
            t_img.setStyleSheet(global_label_style)

            t_name = QLabel()
            t_name.setAlignment(Qt.AlignCenter)
            t_name.setMinimumHeight(30)

            v.addWidget(t_img, alignment=Qt.AlignCenter)
            v.addWidget(t_name, alignment=Qt.AlignCenter)
            talent_layout.addLayout(v)
            self.survivor_talent_images.append(t_img)
            self.survivor_talent_names.append(t_name)

        # 3) BAN 位（来自 survivor_ban）
        self.survivors_ban_box = QGroupBox("BAN 位")
        self.survivors_ban_box.setStyleSheet(inner_groupbox_style)
        ban_layout = QHBoxLayout(self.survivors_ban_box)
        self.survivor_ban_widgets = []
        for _ in range(4):
            ban_w = BanWidget(survivor_ban_names, "survivor_ban")
            ban_layout.addWidget(ban_w)
            self.survivor_ban_widgets.append(ban_w)

        surv_layout.addWidget(self.survivors_info_box)
        surv_layout.addWidget(self.survivors_talent_box)
        surv_layout.addWidget(self.survivors_ban_box)
        self.group_survivors.setLayout(surv_layout)

        # ========== 监管者(1人) ==========
        self.group_hunter = QGroupBox("监管者（1人）")
        self.group_hunter.setStyleSheet(outer_groupbox_style)
        hunter_vlayout = QVBoxLayout(self.group_hunter)
        hunter_vlayout.setSpacing(10)

        # 1) 选手信息
        self.hunter_info_box = QGroupBox("选手信息")
        self.hunter_info_box.setStyleSheet(inner_groupbox_style)
        info_layout_h = QVBoxLayout(self.hunter_info_box)
        self.hunter_avatar_label = QLabel()
        self.hunter_avatar_label.setFixedSize(AVATAR_SIZE, AVATAR_SIZE)
        self.hunter_avatar_label.setAlignment(Qt.AlignCenter)
        self.hunter_avatar_label.setStyleSheet(global_label_style)
        self.hunter_name_label = QLabel()
        self.hunter_name_label.setAlignment(Qt.AlignCenter)
        self.hunter_name_label.setMinimumHeight(30)
        info_layout_h.addWidget(self.hunter_avatar_label, alignment=Qt.AlignCenter)
        info_layout_h.addWidget(self.hunter_name_label, alignment=Qt.AlignCenter)

        # 2) 天赋 & 主动技能
        self.hunter_talent_box = QGroupBox("天赋")
        self.hunter_talent_box.setStyleSheet(inner_groupbox_style)
        talent_layout_h = QVBoxLayout(self.hunter_talent_box)
        self.hunter_talent_image = QLabel()
        self.hunter_talent_image.setFixedSize(TALENT_IMG_SIZE, TALENT_IMG_SIZE)
        self.hunter_talent_image.setAlignment(Qt.AlignCenter)
        self.hunter_talent_image.setStyleSheet(global_label_style)
        self.hunter_talent_name = QLabel()
        self.hunter_talent_name.setAlignment(Qt.AlignCenter)
        self.hunter_talent_name.setMinimumHeight(30)
        talent_layout_h.addWidget(self.hunter_talent_image, alignment=Qt.AlignCenter)
        talent_layout_h.addWidget(self.hunter_talent_name, alignment=Qt.AlignCenter)

        self.hunter_active_box = QGroupBox("主动技能")
        self.hunter_active_box.setStyleSheet(inner_groupbox_style)
        active_layout_h = QVBoxLayout(self.hunter_active_box)
        self.hunter_active_image = QLabel()
        self.hunter_active_image.setFixedSize(ACTIVE_IMG_SIZE, ACTIVE_IMG_SIZE)
        self.hunter_active_image.setAlignment(Qt.AlignCenter)
        self.hunter_active_image.setStyleSheet(global_label_style)
        self.hunter_active_name = QLabel()
        self.hunter_active_name.setAlignment(Qt.AlignCenter)
        self.hunter_active_name.setMinimumHeight(30)
        active_layout_h.addWidget(self.hunter_active_image, alignment=Qt.AlignCenter)
        active_layout_h.addWidget(self.hunter_active_name, alignment=Qt.AlignCenter)

        row_talent_active = QHBoxLayout()
        row_talent_active.addWidget(self.hunter_talent_box)
        row_talent_active.addWidget(self.hunter_active_box)

        # 3) BAN 位（来自 hunter_ban）
        self.hunter_ban_box = QGroupBox("BAN 位")
        self.hunter_ban_box.setStyleSheet(inner_groupbox_style)
        ban_layout_h = QVBoxLayout(self.hunter_ban_box)
        self.hunter_ban_widget = BanWidget(hunter_ban_names, "hunter_ban")
        ban_layout_h.addWidget(self.hunter_ban_widget)

        hunter_vlayout.addWidget(self.hunter_info_box)
        hunter_vlayout.addLayout(row_talent_active)
        hunter_vlayout.addWidget(self.hunter_ban_box)
        self.group_hunter.setLayout(hunter_vlayout)

        # ========== 下排角色(求生者 + 监管者) ==========
        self.group_survivor_roles = QGroupBox("求生者角色(4)")
        self.group_survivor_roles.setStyleSheet(outer_groupbox_style)
        surv_roles_layout = QHBoxLayout(self.group_survivor_roles)
        self.survivor_role_cards = []
        for _ in range(4):
            c = self._createRoleCard()
            surv_roles_layout.addWidget(c)
            self.survivor_role_cards.append(c)

        self.group_hunter_roles = QGroupBox("监管者角色(4)")
        self.group_hunter_roles.setStyleSheet(outer_groupbox_style)
        hunt_roles_layout = QHBoxLayout(self.group_hunter_roles)
        self.hunter_role_cards = []
        for _ in range(4):
            c = self._createRoleCard()
            hunt_roles_layout.addWidget(c)
            self.hunter_role_cards.append(c)

        # ========== 地图区域 ==========
        self.group_map = QGroupBox("地图")
        self.group_map.setStyleSheet(outer_groupbox_style)
        map_layout = QVBoxLayout(self.group_map)
        map_layout.setSpacing(10)
        self.map_image_label = QLabel()
        self.map_image_label.setFixedSize(MAP_IMG_SIZE, int(0.5 * MAP_IMG_SIZE))
        self.map_image_label.setStyleSheet(global_label_style)
        self.map_image_label.setAlignment(Qt.AlignCenter)
        self.map_name_label = QLabel()
        self.map_name_label.setAlignment(Qt.AlignCenter)
        self.map_name_label.setMinimumHeight(30)

        
        map_layout.addWidget(self.map_image_label, alignment=Qt.AlignCenter)
        map_layout.addWidget(self.map_name_label, alignment=Qt.AlignCenter)

        # 布局
        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(self.group_survivors,      0, 0)
        grid.addWidget(self.group_hunter,         0, 1)
        grid.addWidget(self.group_survivor_roles, 1, 0)
        grid.addWidget(self.group_hunter_roles,   1, 1)
        grid.setColumnStretch(0, 1)
        grid.setColumnStretch(1, 1)
        main_layout.addLayout(grid)
        main_layout.addWidget(self.group_map)




        # 绑定按钮事件
        self.btn_draw_players.clicked.connect(self.assign_players)
        self.btn_survivor_role.clicked.connect(self.assign_survivor_roles)
        self.btn_hunter_role.clicked.connect(self.assign_hunter_roles)
        self.btn_survivor_talent.clicked.connect(self.assign_survivor_talents)
        self.btn_hunter_talent.clicked.connect(self.assign_hunter_talent)
        self.btn_hunter_active_skill.clicked.connect(self.assign_hunter_active_skill)
        self.btn_map.clicked.connect(self.assign_map)
        self.btn_one_key.clicked.connect(self.one_key_extract)
        self.btn_reset.clicked.connect(self.reset_all)

    def assign_players(self):
        """同时抽取求生者 4 名 + 监管者 1 名"""
        self.assign_survivor_names()
        self.assign_hunter_name()

        # 把刚抽到的名字立即写入上一把黑名单
        if self.this_match_survivors and self.this_match_hunter:
            self.last_match_players = set(self.this_match_survivors)
            self.last_match_players.add(self.this_match_hunter)

        # 调试打印
        print(">>> 本场求生者:", self.this_match_survivors)
        print(">>> 本场监管者:", self.this_match_hunter)
        print(">>> 黑名单(last_match_players):", self.last_match_players)

    def _createRoleCard(self):
        w = QWidget()
        layout = QVBoxLayout(w)
        layout.setContentsMargins(10,10,10,10)
        layout.setSpacing(10)
        img_label = QLabel()
        img_label.setFixedSize(ROLE_IMG_SIZE, ROLE_IMG_SIZE)
        img_label.setAlignment(Qt.AlignCenter)
        img_label.setStyleSheet(global_label_style)
        name_label = QLabel()
        name_label.setAlignment(Qt.AlignCenter)
        name_label.setMinimumHeight(30)
        layout.addWidget(img_label, alignment=Qt.AlignCenter)
        layout.addWidget(name_label, alignment=Qt.AlignCenter)
        w.img_label = img_label
        w.name_label = name_label
        return w

    # ========== 抽选逻辑 ==========
    def assign_survivor_names(self):
        available = set(survivor_avatar_names) - self.last_match_players
        if self.this_match_hunter:
            available -= {self.this_match_hunter}
        if self.prev_draw_survivors:
            available -= self.prev_draw_survivors
        if len(available) < 4:
            return
        self.this_match_survivors = random.sample(available, 4)
        self.prev_draw_survivors = set(self.this_match_survivors)
        for i, name in enumerate(self.this_match_survivors):
            pix = self.load_avatar(name, True)
            self.survivor_avatar_labels[i].setPixmap(pix)
            if pix.isNull():
                self.survivor_avatar_labels[i].setStyleSheet(global_label_style)
            else:
                self.survivor_avatar_labels[i].setStyleSheet("")
            self.survivor_name_labels[i].setText(name)

    def assign_hunter_name(self):
        available = set(hunter_avatar_names) - self.last_match_players
        if self.this_match_survivors:
            available -= set(self.this_match_survivors)
        if self.prev_draw_hunter:
            available -= {self.prev_draw_hunter}
        if not available:
            return
        selected = random.choice(list(available))
        self.this_match_hunter = selected
        self.prev_draw_hunter = selected
        pix = self.load_avatar(selected, False)
        self.hunter_avatar_label.setPixmap(pix)
        if pix.isNull():
            self.hunter_avatar_label.setStyleSheet(global_label_style)
        else:
            self.hunter_avatar_label.setStyleSheet("")
        self.hunter_name_label.setText(selected)

    def assign_survivor_roles(self):
        if len(survivor_role_names) < 4:
            return
        selected = random.sample(survivor_role_names, 4)
        for i, role_name in enumerate(selected):
            c = self.survivor_role_cards[i]
            c.img_label.clear()
            c.img_label.setStyleSheet(global_label_style)
            c.name_label.clear()
            pix = self.load_role_image(role_name, True)
            c.img_label.setPixmap(pix)
            if not pix.isNull():
                c.img_label.setStyleSheet("")
            c.name_label.setText(role_name)

    def assign_hunter_roles(self):
        if len(hunter_role_names) < 4:
            return
        selected = random.sample(hunter_role_names, 4)
        for i, role_name in enumerate(selected):
            c = self.hunter_role_cards[i]
            c.img_label.clear()
            c.img_label.setStyleSheet(global_label_style)
            c.name_label.clear()
            pix = self.load_role_image(role_name, False)
            c.img_label.setPixmap(pix)
            if not pix.isNull():
                c.img_label.setStyleSheet("")
            c.name_label.setText(role_name)

    def assign_survivor_talents(self):
        if not survivor_talent_names:
            return
        for i in range(4):
            t = random.choice(survivor_talent_names)
            pix = self.load_talent_image(t, True)
            self.survivor_talent_images[i].setPixmap(pix)
            if pix.isNull():
                self.survivor_talent_images[i].setStyleSheet(global_label_style)
            else:
                self.survivor_talent_images[i].setStyleSheet("")
            self.survivor_talent_names[i].setText(t)

    def assign_hunter_talent(self):
        if not hunter_talent_names:
            return
        t = random.choice(hunter_talent_names)
        pix = self.load_talent_image(t, False)
        self.hunter_talent_image.setPixmap(pix)
        if pix.isNull():
            self.hunter_talent_image.setStyleSheet(global_label_style)
        else:
            self.hunter_talent_image.setStyleSheet("")
        self.hunter_talent_name.setText(t)

    def assign_hunter_active_skill(self):
        if not active_ability_names:
            return
        s = random.choice(active_ability_names)
        pix = self.load_active_ability_image(s)
        self.hunter_active_image.setPixmap(pix)
        if pix.isNull():
            self.hunter_active_image.setStyleSheet(global_label_style)
        else:
            self.hunter_active_image.setStyleSheet("")
        self.hunter_active_name.setText(s)

    def assign_map(self):
        if not map_names:
            return
        m = random.choice(map_names)
        pix = self.load_map_image(m)
        self.map_image_label.setPixmap(pix)
        if pix.isNull():
            self.map_image_label.setStyleSheet(global_label_style)
        else:
            self.map_image_label.setStyleSheet("")
        self.map_name_label.setText(m)

    def one_key_extract(self):
        """一键抽取：求生者/监管者选手、角色、天赋、主动技能、地图；最后自动更新上一场记录。"""
        self.assign_survivor_names()
        self.assign_hunter_name()
        self.assign_survivor_roles()
        self.assign_hunter_roles()
        self.assign_survivor_talents()
        self.assign_hunter_talent()
        self.assign_hunter_active_skill()
        self.assign_map()

        # 自动确认(更新 last_match_players)
        if self.this_match_survivors and self.this_match_hunter:
            all_this = set(self.this_match_survivors)
            all_this.add(self.this_match_hunter)
            self.last_match_players = all_this.copy()
            self.this_match_survivors.clear()
            self.this_match_hunter = None
            self.prev_draw_survivors.clear()
            self.prev_draw_hunter = None

    def reset_all(self):
        # self.last_match_players.clear()
        self.this_match_survivors.clear()
        self.this_match_hunter = None
        self.prev_draw_survivors.clear()
        self.prev_draw_hunter = None

        for i in range(4):
            self.survivor_avatar_labels[i].clear()
            self.survivor_avatar_labels[i].setStyleSheet(global_label_style)
            self.survivor_name_labels[i].clear()

            self.survivor_talent_images[i].clear()
            self.survivor_talent_images[i].setStyleSheet(global_label_style)
            self.survivor_talent_names[i].clear()

            self.survivor_ban_widgets[i].reset()

        self.hunter_avatar_label.clear()
        self.hunter_avatar_label.setStyleSheet(global_label_style)
        self.hunter_name_label.clear()
        self.hunter_talent_image.clear()
        self.hunter_talent_image.setStyleSheet(global_label_style)
        self.hunter_talent_name.clear()
        self.hunter_active_image.clear()
        self.hunter_active_image.setStyleSheet(global_label_style)
        self.hunter_active_name.clear()
        self.hunter_ban_widget.reset()

        for c in self.survivor_role_cards:
            c.img_label.clear()
            c.img_label.setStyleSheet(global_label_style)
            c.name_label.clear()

        for c in self.hunter_role_cards:
            c.img_label.clear()
            c.img_label.setStyleSheet(global_label_style)
            c.name_label.clear()

        self.map_image_label.clear()
        self.map_image_label.setStyleSheet(global_label_style)
        self.map_name_label.clear()

    # ========== 资源加载函数 (含求生者角色裁剪) ==========
    def load_avatar(self, name, is_survivor=True):
        folder = "survivor_avarter" if is_survivor else "hunter_avarter"
        path = os.path.join("images", folder, f"{name}.jpg")
        pix = QPixmap(path)
        if pix.isNull():
            return QPixmap()
        return self.make_round_pixmap(pix, AVATAR_SIZE)

    def load_role_image(self, role_name, is_survivor=True):
        folder = "survivor" if is_survivor else "hunter"
        path = os.path.join("images", folder, f"{role_name}.jpg")
        pix = QPixmap(path)
        if pix.isNull():
            return QPixmap()
        if is_survivor:
            w = pix.width()
            h = pix.height()
            new_h = int(h * 0.6)  # 上半部分
            pix = pix.copy(0, 0, w, new_h)
        return pix.scaled(ROLE_IMG_SIZE, ROLE_IMG_SIZE, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    def load_talent_image(self, talent_name, is_survivor=True):
        folder = "survivor_talent" if is_survivor else "hunter_talent"
        path = os.path.join("images", folder, f"{talent_name}.jpg")
        pix = QPixmap(path)
        if pix.isNull():
            return QPixmap()
        return pix.scaled(TALENT_IMG_SIZE, TALENT_IMG_SIZE, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    def load_active_ability_image(self, skill_name):
        path = os.path.join("images", "active_ability", f"{skill_name}.jpg")
        pix = QPixmap(path)
        if pix.isNull():
            return QPixmap()
        return pix.scaled(ACTIVE_IMG_SIZE, ACTIVE_IMG_SIZE, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    def load_map_image(self, map_name):
        path = os.path.join("images", "map", f"{map_name}.jpg")
        pix = QPixmap(path)
        if pix.isNull():
            return QPixmap()
        return pix.scaled(MAP_IMG_SIZE, MAP_IMG_SIZE, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    def make_round_pixmap(self, pixmap, size=100):
        pixmap = pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        w = pixmap.width()
        h = pixmap.height()
        side = min(w, h)
        final_pix = QPixmap(side, side)
        final_pix.fill(Qt.transparent)
        painter = QPainter(final_pix)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setBrush(Qt.white)
        painter.drawEllipse(0, 0, side, side)
        painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        painter.drawPixmap((side - w)//2, (side - h)//2, pixmap)
        painter.end()
        return final_pix
